package main

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcache"
	"github.com/gookit/event"
	"seawolf-admin-go/internal/app/admin/routers"
	"seawolf-admin-go/internal/consts"
	allrouters "seawolf-admin-go/internal/routers"
	"seawolf-admin-go/utility/response"
)

func regEventBus() {
	// 注册事件总线
	event.On(consts.AsynqEventUserConfirmScore, event.ListenerFunc(func(e event.Event) error {
		//g.Dump(e)
		return nil
	}), event.Normal)
}

func main() {
	defaultVersion := "1.0.0"
	// 适配数据库查询缓存为 Redis
	redisCache := gcache.NewAdapterRedis(g.Redis())
	g.DB().GetCache().SetAdapter(redisCache)

	s := g.Server()
	s.BindHandler("/", func(r *ghttp.Request) {
		r.Response.Write("api ok")
	})
	// 注册中间件，统一处理返回值
	s.BindMiddlewareDefault(allrouters.MiddlewareHandlerResponse)
	// 统一错误处理
	s.BindMiddlewareDefault(allrouters.MiddlewareErrorHandler)

	// 严格模式
	// 登录中间件
	s.BindMiddlewareDefault(allrouters.MiddlewareHandlerIsLogin)
	// 权限判断中间件
	s.BindMiddlewareDefault(allrouters.MiddlewareHandlerIsPermission)

	// 注册路由
	routers.Reg(s, defaultVersion)
	// 注册404
	s.BindStatusHandler(404, func(r *ghttp.Request) {
		// 注意，这里是先过了 中间件后才执行的，所以需要清除前面的内容
		r.Response.ClearBuffer()
		response.JsonExit(r, 404, "Not Found")
	})

	staticServer := g.Server("static")
	staticServer.SetIndexFolder(true)
	ctx := context.Background()
	rootPathTmp, _ := g.Cfg().Get(ctx, "upload.WwwrootPath", "")
	serverPortTmp, _ := g.Cfg().Get(ctx, "upload.StaticServerPort", 8912)
	staticServer.SetServerRoot(rootPathTmp.String())
	staticServer.SetPort(serverPortTmp.Int())
	err := staticServer.Start()
	if err != nil {
		panic(err)
	}

	s.Run()
}
